package com.qianfeng.openapi.monitor.job;

import com.qianfeng.openapi.monitor.feign.CacheServiceClient;
import com.qianfeng.openapi.monitor.feign.SearchServiceClient;
import com.qianfeng.openapi.monitor.utils.EmailUtils;
import com.qianfeng.openapi.monitor.utils.QuartzUtils;
import com.qianfeng.openapi.monitor.utils.SpringUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Map;

/**
 * @Description:
 * @Company: 千锋互联
 * @Author: 李丽婷
 * @Date: 2021/1/5
 * @Time: 下午2:14
 */
@Component
public class MyJOb implements Job {

    @PostConstruct  //init
    public  void  init(){
        QuartzUtils.createTask("MyJob","*/5 * * * * ?","myTrigger");
    }

    //@PreDestroy // destorty


    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        //System.out.println("helloword");
        CacheServiceClient cacheServiceClient =(CacheServiceClient) SpringUtils.getBean(CacheServiceClient.class);
        boolean lock = cacheServiceClient.lock("lock",100);
        System.out.println("------>"+lock);
        if (lock){
            SearchServiceClient client =(SearchServiceClient) SpringUtils.getBean(SearchServiceClient.class);

            //半小时以内 api平均调用时间
            long now = System.currentTimeMillis();
            //Map<String, Integer> map =  client.statAvg(now-(30*60*1000),now);
            Map<String, Integer> map =  client.statAvg(now-(60*60*1000),now);
            for(Map.Entry<String,Integer> entry:map.entrySet()){
                System.out.println(entry.getKey()+"平均调用时间"+entry.getValue());
                //设置一个临界值
                int avg = 3000;//3秒
                if (entry.getValue()>avg){
                    EmailUtils.sendMail(entry.getKey()+"告警⚠️",entry.getKey()+"调用超时，请处理！");
                }
            }

            //用完后释放锁
            cacheServiceClient.delKey("lock");
        }

    }
}
